Estudiante: Dennis Xiloj
Carnet: 22006829
Resuelva los siguientes problemas dejando constancia de todo su trabajo con la mayor claridad posible. Usted puede utilizar recursos tales como: notas de clase, laboratorios, vídeos de clase, libros, etc.; La única ayuda que esta terminantemente PROHIBIDA es la de otra persona, su respuesta debe ser razonada y desarrollada PERSONALMENTE. En el GES se encuentra un dataset llamado Dataset Presidentes EEUU, con dicho dataset debe responder lo siguiente:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
import plotly.express as px
import plotly
plotly.offline.init_notebook_mode()
# leer el archivo 1976-2020-president.csv
presidents = pd.read_csv('1976-2020-president.csv')
presidents
| year | state | state_po | state_fips | state_cen | state_ic | office | candidate | party_detailed | writein | candidatevotes | totalvotes | version | notes | party_simplified | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1976 | ALABAMA | AL | 1 | 63 | 41 | US PRESIDENT | CARTER, JIMMY | DEMOCRAT | False | 659170 | 1182850 | 20210113 | NaN | DEMOCRAT |
| 1 | 1976 | ALABAMA | AL | 1 | 63 | 41 | US PRESIDENT | FORD, GERALD | REPUBLICAN | False | 504070 | 1182850 | 20210113 | NaN | REPUBLICAN |
| 2 | 1976 | ALABAMA | AL | 1 | 63 | 41 | US PRESIDENT | MADDOX, LESTER | AMERICAN INDEPENDENT PARTY | False | 9198 | 1182850 | 20210113 | NaN | OTHER |
| 3 | 1976 | ALABAMA | AL | 1 | 63 | 41 | US PRESIDENT | BUBAR, BENJAMIN ""BEN"" | PROHIBITION | False | 6669 | 1182850 | 20210113 | NaN | OTHER |
| 4 | 1976 | ALABAMA | AL | 1 | 63 | 41 | US PRESIDENT | HALL, GUS | COMMUNIST PARTY USE | False | 1954 | 1182850 | 20210113 | NaN | OTHER |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 4282 | 2020 | WYOMING | WY | 56 | 83 | 68 | US PRESIDENT | JORGENSEN, JO | LIBERTARIAN | False | 5768 | 278503 | 20210113 | NaN | LIBERTARIAN |
| 4283 | 2020 | WYOMING | WY | 56 | 83 | 68 | US PRESIDENT | PIERCE, BROCK | INDEPENDENT | False | 2208 | 278503 | 20210113 | NaN | OTHER |
| 4284 | 2020 | WYOMING | WY | 56 | 83 | 68 | US PRESIDENT | NaN | NaN | True | 1739 | 278503 | 20210113 | NaN | OTHER |
| 4285 | 2020 | WYOMING | WY | 56 | 83 | 68 | US PRESIDENT | OVERVOTES | NaN | False | 279 | 278503 | 20210113 | NaN | OTHER |
| 4286 | 2020 | WYOMING | WY | 56 | 83 | 68 | US PRESIDENT | UNDERVOTES | NaN | False | 1459 | 278503 | 20210113 | NaN | OTHER |
4287 rows × 15 columns
# cantidad de votos por cada eleccion
votes = presidents[['year', 'candidatevotes']].groupby(['year']).sum()
votes['millions'] = votes['candidatevotes'].apply(lambda x: f'{x/1e6:.2f}M')
fig = px.line(votes, x=votes.index, y='candidatevotes', markers=True,
title='Total de votos por elección presidencial en EEUU de 1976 a 2020',
labels={'candidatevotes': 'Votos', 'year': 'Año'},
text='millions',
)
fig.update_traces(textposition='top center')
fig.update_xaxes(type='category')
fig.show()
def votos_eleccion(year):
"""Grafica lo votos por cada candidato del año pasado como parametro"""
votos = presidents[presidents['year'] == year][['candidate', 'candidatevotes']].groupby('candidate').sum()
votos['millions'] = votos['candidatevotes'].apply(lambda x: f'{x/1e6:.2f}M')
votos.sort_values(by='candidatevotes', ascending=False, inplace=True)
fig = px.bar(votos, x=votos.index, y='candidatevotes',
title=f'Votos por candidato en las elecciones de {year} en EEUU',
labels={'candidate': 'Candidato', 'y': 'Votos'},
text='millions'
)
fig.show()
# probamos la funcion
votos_eleccion(1976)
votos_eleccion(1980)
# % de votos obtenidos por cada ganador
ganadores = pd.read_html('https://en.wikipedia.org/wiki/List_of_presidents_of_the_United_States')
ganadores = ganadores[1]
ganadores = ganadores[['Name(Birth–Death)', 'Election', 'Vice President']]
# rename the Name(Birth–Death) column
ganadores.rename(columns={'Name(Birth–Death)': 'name_birth', 'Election': 'election', 'Vice President': 'vicepresident'}, inplace=True)
# drop the last row
ganadores = ganadores.drop(ganadores.index[-1])
# convertir los datos de ganador (nacimiento-muerte) en 2 columnas
columnas_nombre = ganadores['name_birth'].str.rsplit('(', expand=True).rename(columns={0: 'name', 1: 'birth'})
# el nombre lo necesitamos en mayusculas y en la forma APELLIDO, NOMBRE
columnas_nombre['name'] = columnas_nombre['name'].str.upper()
ganadores = ganadores.join(columnas_nombre['name'].str.rsplit(' ', n=1, expand=True).rename(columns={0: 'firstname', 1: 'lastname'}))
ganadores['winner'] = ganadores['lastname'] + ', ' + ganadores['firstname']
# convertir election en numerico
ganadores['election'] = ganadores['election'].str.replace('–.*$', '', regex=True).astype(int)
ganadores
| name_birth | election | vicepresident | firstname | lastname | winner | |
|---|---|---|---|---|---|---|
| 0 | George Washington(1732–1799) | 1788 | John Adams[c] | GEORGE | WASHINGTON | WASHINGTON, GEORGE |
| 1 | George Washington(1732–1799) | 1792 | John Adams[c] | GEORGE | WASHINGTON | WASHINGTON, GEORGE |
| 2 | John Adams(1735–1826) | 1796 | Thomas Jefferson[d] | JOHN | ADAMS | ADAMS, JOHN |
| 3 | Thomas Jefferson(1743–1826) | 1800 | Aaron Burr | THOMAS | JEFFERSON | JEFFERSON, THOMAS |
| 4 | Thomas Jefferson(1743–1826) | 1804 | George Clinton[e] | THOMAS | JEFFERSON | JEFFERSON, THOMAS |
| ... | ... | ... | ... | ... | ... | ... |
| 77 | George W. Bush(b. 1946) | 2004 | Dick Cheney | GEORGE W. | BUSH | BUSH, GEORGE W. |
| 78 | Barack Obama(b. 1961) | 2008 | Joe Biden | BARACK | OBAMA | OBAMA, BARACK |
| 79 | Barack Obama(b. 1961) | 2012 | Joe Biden | BARACK | OBAMA | OBAMA, BARACK |
| 80 | Donald Trump(b. 1946) | 2016 | Mike Pence | DONALD | TRUMP | TRUMP, DONALD |
| 81 | Joe Biden(b. 1942) | 2020 | Kamala Harris | JOE | BIDEN | BIDEN, JOE |
82 rows × 6 columns
presidents = presidents.merge(ganadores[['election', 'vicepresident', 'winner']], left_on='year', right_on='election', how='left')
# corregir los nombres de los ganadores que no coinciden al 100%
# BUSH, GEORGE H.W. debe ser BUSH, GEORGE H. W.
presidents['candidate'] = presidents['candidate'].str.replace('BUSH, GEORGE H.W.', 'BUSH, GEORGE H. W.', regex=False)
# OBAMA, BARACK H. debe ser OBAMA, BARACK
presidents['candidate'] = presidents['candidate'].str.replace('OBAMA, BARACK H.', 'OBAMA, BARACK', regex=False)
# TRUMP, DONALD J. debe ser TRUMP, DONALD
presidents['candidate'] = presidents['candidate'].str.replace('TRUMP, DONALD J.', 'TRUMP, DONALD', regex=False)
# BIDEN, JOSEPH R. JR debe ser BIDEN, JOE
presidents['candidate'] = presidents['candidate'].str.replace('BIDEN, JOSEPH R. JR', 'BIDEN, JOE', regex=False)
# merge del dataset csv con los datos de ganadores desde wikipedia
presidents['won'] = presidents['candidate'] == presidents['winner']
# revisamos que todos los años tengan un ganador
presidents.groupby('year')['won'].any()
year 1976 True 1980 True 1984 True 1988 True 1992 True 1996 True 2000 True 2004 True 2008 True 2012 True 2016 True 2020 True Name: won, dtype: bool
# obtener los totales de votos para cada año y candidato
candidatevotes = presidents[presidents['won']][['year', 'candidate', 'candidatevotes']].groupby(['year', 'candidate']).sum()
totalvotes = presidents[['year', 'candidatevotes']].groupby(['year']).sum()
# calcular el porcentaje
candidatevotes = candidatevotes.reset_index().set_index('year')
candidatevotes['totalvotes'] = totalvotes['candidatevotes']
candidatevotes['percent'] = candidatevotes['candidatevotes'] / candidatevotes['totalvotes'] * 100
candidatevotes['prettypercent'] = candidatevotes['percent'].round(2).astype(str) + '%'
# agregar una columna para el label del año
candidatevotes['year_winner'] = candidatevotes.index.astype(str) + ' (' + candidatevotes['candidate'] + ')'
# graficar
fig = px.bar(candidatevotes, x='year_winner', y='percent',
title='Porcentaje de votos por candidato ganador en las elecciones de EEUU de 1976 a 2020',
labels={'year_winner': 'Año (ganador)', 'percent': 'Porcentaje'},
text='prettypercent'
)
fig.update_yaxes(range=[40, 60])
fig.show()
def votos_partido(year):
"""Crea una grafica de votos x partido para el año pasado como parametro"""
votos = presidents[presidents['year'] == year][['party_detailed', 'candidatevotes']].groupby('party_detailed').sum()
votos['millions'] = votos['candidatevotes'].apply(lambda x: f'{x/1e6:.2f}M' if x > 1e5 else f'{x/1e3:.2f}K' if x > 1e3 else str(x))
votos.sort_values(by='candidatevotes', ascending=False, inplace=True)
fig = px.bar(votos, x=votos.index, y='candidatevotes',
title=f'Votos por partido en las elecciones de {year} en EEUU',
labels={'party_detailed': 'Partido', 'candidatevotes': 'Votos'},
text='millions',
)
fig.show()
# probar la funcion
votos_partido(1976)
votos_partido(2020)
def votos_eleccion_estado(year, state):
votos = presidents[(presidents['year'] == year) & (presidents['state'] == state.upper())][['candidate', 'candidatevotes']].groupby('candidate').sum()
votos['millions'] = votos['candidatevotes'].apply(lambda x: f'{x/1e6:.2f}M' if x > 1e5 else f'{x/1e3:.2f}K' if x > 1e3 else str(x))
votos.sort_values(by='candidatevotes', ascending=False, inplace=True)
fig = px.bar(votos, x=votos.index, y='candidatevotes',
title=f'Votos por candidato en las elecciones de {year} en {state}',
labels={'candidate': 'Candidato', 'candidatevotes': 'Votos'},
text='millions',
)
fig.show()
# probar la funcion
votos_eleccion_estado(2020, 'California')
votos_eleccion_estado(2020, 'Texas')